import pyvisa
import time


class GWinstek(object):
    def __init__(self, gpib_addr):
        object.__init__(self)
        localResources = pyvisa.ResourceManager()
        # print(localResources.FindResources("?*"))
        self.addr = gpib_addr
        self.ql = localResources.open_resource("GPIB0::%i::INSTR" % gpib_addr)
        # self.id =

    def shutDown(self):
        if self.ql != None:
            self.outOff()
            self.ql.write("LOCAL")

    def getid(self):
        self.id = self.ql.query("*IDN?")
        return self.id

    def clear(self):
        self.ql.write("*RST")

    def setV(self, channel, voltage, current):
        # set V output to a given value
        self.ql.write(":CHAN%s:VOLT %f;CHAN%s:CURR %f" % (channel, voltage, channel, current))

    def setIlim(self, value):
        ''' set I limit on output to a given value '''
        self.ql.write("I1 %f" % value)

    def getCurrent(self, channel):
        curr = self.ql.query(":CHAN%s:MEAS:CURR?" %channel)
        print "hi"
        return curr

    def setCh(self, ch_number=1, voltage=None, Ilim=1.5):
        ''' turns ON the output 1~3'''
        self.ql.write("SOURce:CHANnel %s" % ch_number)
        self.ql.write("SOURce:VOLTage %f" % voltage)
        self.ql.write("SOURce:CURRent %f" % Ilim)

    def outOn(self):
        ''' turns ON the output '''
        self.ql.write("OUTPut:STATe 1 ")

    def outOff(self):
        ''' turns OFF the output '''
        self.ql.write("OUTPut:STATe 0 ")




# pwr = GWinstek(8)
# # print pwr.getid()
# time.sleep(1)
# print pwr.getCurrent(1)

# while True:
#     pwr.clear()
#     pwr.outOn()
#     time.sleep(5)
#     for i in range(0, 11, 1):
#         pwr.setV(1, i, 0.5)
#         time.sleep(1)
#     for j in range(9, 20, 1):
#         pwr.setV(2, j, 0.5)
#         time.sleep(1)
#     for k in range(0, 6, 1):
#         pwr.setV(3, k, 0.1)
#         time.sleep(1)
#     pwr.outOff()
#     time.sleep(5)
